<template>
  <view @tap="chooseImg">
    <slot></slot>
  </view>
</template>
<script>
import * as ocr from "./index.js";
	export default {
		data() {
			return {
			}
		},
		props: {
			count: {
				type: Number,
				default: 9
			},
			sizeType: {
				type: Array,
				default: () => ['original','compressed']
			},
			sourceType: {
				type: Array,
				default: () => ['album','camera']
			}
		},
		methods: {
			//图片转文字
			getImgText(imgInfo) {
				let result = new Promise((resolve, reject) => {
					ocr.init().then(() => {
						const img = new Image();
						img.src = imgInfo;
						img.onload = async () => {
							const results = await ocr.recognize(img); // 使用recognize方法执行OCR识别
							resolve(results);
						}
						img.onerror = (err) => {
							reject(err);
						}
					})
				})
				return result;
			},
			//选择图片
			chooseImg() {
				uni.chooseImage({
					count: 1,
					sizeType: this.sizeType,
					sourceType: this.sourceType,
					success: (res) => {
						this.$emit('chooseImg',res);
						res.tempFilePaths.map(item => {
							this.getImgText(item).then(res => {
								this.$emit('ocrSuccess', res);
							}).catch(err => {
								this.$emit('ocrFail', err);
							})
						})
					},
					fail: (err) => {
						this.$emit('ocrFail', err);
					}
				})
			},
		}
	}
</script>